package calvin.study.rabbitmq.tasker;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import calvin.study.rabbitmq.dao.RabbitMqMessageLogDao;
import calvin.study.rabbitmq.model.order.Order;
import calvin.study.rabbitmq.model.rabbitmq.RabbitMqMessageLog;
import calvin.study.rabbitmq.model.rabbitmq.enums.OrderSendStatusEnum;
import calvin.study.rabbitmq.mq.RabbitOrderSender;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;

@Component
public class RetryMessageTasker {

	@Autowired
	private RabbitMqMessageLogDao mqMessageLogDao;
	@Autowired
	private RabbitOrderSender rabbitOrderSender;

	// 项目启动3s后，每隔10s扫描一次
	@Scheduled(initialDelay = 3000, fixedDelay = 10000)
	public void run() {
		System.out.println("-------------------"+DateUtil.date()+"定时任务开始---------------------------");
		// 获取已超时的消息
		List<RabbitMqMessageLog> mqMsgList = mqMessageLogDao.query4StatusAndTimeoutMessage();
		for (RabbitMqMessageLog log : mqMsgList) {
			if (log.getTryCount() >= 3) {
				// 超过最大尝试次数标记为失败，人工处理
				mqMessageLogDao.changeBrokerMessageLogStatus(log.getBusiId(), OrderSendStatusEnum.ORDER_FAIL.getCode(),
						DateUtil.date());
			} else {
				mqMessageLogDao.update4ReSend(log.getMessageId(), DateUtil.date());
				Order order = JSONUtil.toBean(log.getMessage(), Order.class);
				try {
					rabbitOrderSender.sendOrder(order);
				} catch (Exception e) {
					e.printStackTrace();
					System.err.println("消息发送失败");
				}
			}
		}
	}

	public static void main(String[] args) {
		Order order = JSONUtil.toBean("{\"orderId\":\"1491310392218095616\",\"orderName\":\"商品订单6\"}", Order.class);
		System.out.println(order);
		
	}
}
